package controller.menubar.commands;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;


import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;

import javax.swing.SwingWorker;
import view.MainFrame;


@SuppressWarnings("unused")
public class FileSystemWatcher extends SwingWorker<Void, Void>{
	
	public FileSystemWatcher(MainFrame frame , File fileArea) {		
		this.frame = frame;
		this.fileArea = fileArea;
	}	
	
	public FileSystemWatcher(MainFrame frame) {		
		this.frame = frame;		
	}	

	@Override
	protected Void doInBackground() throws Exception {
		startScaning();
		return null;
	}
	
	public File getFileArea() {
		return fileArea;
	}

	public void setFileArea(File fileArea) {
		this.fileArea = fileArea;
	}
	

	
	synchronized public void startScaning() throws IOException, InterruptedException {
		
		FileSystem fileSystem = FileSystems.getDefault();
	  
		 WatchService watchService = fileSystem.newWatchService();
	
	        Map<WatchKey, Path> keyMap = new HashMap<WatchKey, Path>();
	        Path path = Paths.get(fileArea.getAbsolutePath());
	        //keyMap.put(path.register(watchService, ENTRY_CREATE, ENTRY_DELETE,ENTRY_MODIFY), path);	
	        keyMap.put(path.register(watchService, ENTRY_CREATE, ENTRY_DELETE), path);	
	        
	        do {
	            watchKey = watchService.take();
	            Path eventDir = keyMap.get(watchKey);
	            for (WatchEvent<?> event : watchKey.pollEvents()) {
	                //WatchEvent.Kind kind = event.kind();
	                //Path eventPath = (Path) event.context();
	                //System.out.println(eventDir + ": " + event.kind() + ": " + event.context());
	                frame.getMainPanel().getPrimary().getDiskContent().CreateNewView(null);
	        		frame.getMainPanel().getSecondary().getDiskContent().CreateNewView(null);
	        		
	            }
	        } while (watchKey.reset());
	}
	
	
	

	private MainFrame frame;
	private File fileArea;
	private WatchKey watchKey;
	

}
